package com.sc.admin.common.util;

import com.github.benmanes.caffeine.cache.Cache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class CacheUtils {
    private static Cache<String, Object> manualCacheSevenDay;
    private static Cache<String, Object> manualCacheFiveSecond;
    private static CacheManager cacheManager;

    @Autowired
    public CacheUtils(Cache manualCacheSevenDay, Cache manualCacheFiveSecond, CacheManager cacheManager) {
        CacheUtils.manualCacheSevenDay = manualCacheSevenDay;
        CacheUtils.manualCacheFiveSecond = manualCacheFiveSecond;
        CacheUtils.cacheManager = cacheManager;
    }

    public static void set(String key, Object obj) {
        if (key == null) return;
        manualCacheSevenDay.put(key, obj);
    }

    private static Object innerGet(String key) {
        if (key == null) return null;
        return manualCacheSevenDay.getIfPresent(key);
    }

    /**
     * 获取缓存
     *
     * @param key 缓存key
     * @return 缓存值
     */
    public static String get(String key) {
        Object object = innerGet(key);
        return object == null ? null : (String) object;
    }

    public static String get(String key, String defaultValue) {
        String resultData = get(key);
        if (ObjUtils.isEmpty(resultData)) {
            return defaultValue;
        }
        return resultData;
    }

    /**
     * 获取缓存
     *
     * @param key 缓存key
     * @return 缓存值
     */
    public static Object getObj(String key) {
        return innerGet(key);
    }

    public static <T> T getObj(String key, Class<T> clazz) {
        Object obj = innerGet(key);
        if (obj != null) {
            return clazz.cast(obj);
        }
        return null;
    }

    /**
     * 删除缓存
     *
     * @param key 缓存key
     */
    public static void delete(String key) {
        if (key == null) return;
        manualCacheSevenDay.invalidate(key);
    }

    /**
     * 删除默认缓存管理器的缓存
     *
     * @param key 缓存key
     */
    public static void delDefault(String name, String key) {
        if (name == null || key == null) return;
        org.springframework.cache.Cache managerCache = cacheManager.getCache(name);
        managerCache.evictIfPresent(key);
    }

    public static boolean tryLock(String key) {

        Object object = manualCacheFiveSecond.getIfPresent(key);
        if (object == null) {
            manualCacheFiveSecond.put(key, "lock");
            return true;
        }
        return false;
    }

}